
type fn = (...args: any[]) => any

/**
 * 函数防抖：适合只执行一次的情况，例如搜索框中的自动完成，在停止输入后提交一次ajax请求
 * @param {*} fn
 * @param {*} wait
 */
export function debounce(fn: fn, wait = 250) {
  let timeout: number | null

  function debounced(...args: any[]) {
    console.log(timeout, 'tou')
    if (timeout) {
      clearTimeout(timeout)
    }

    timeout = setTimeout(() => {
      fn.apply(this, args)
    }, wait)
  }

  debounced.cancel = () => {
    timeout && clearTimeout(timeout)
  }

  return debounced
}

export function frameDebounce(fn: fn) {
  let wait = false

  return function (...args: any[]) {
    if (wait) { return }

    wait = true
    window.requestAnimationFrame(() => {
      fn.apply(this, args)
      wait = false
    })
  }
}

/**
* @desc 函数节流
* @param func 函数
* @param wait 延迟执行毫秒数
*/

export function throttle<T extends fn>(
  func: T,
  limit: number
): (...args: Parameters<T>) => void {
  let lastCall = 0

  return function (this: any, ...args: Parameters<T>) {
    const now = Date.now()

    if (now - lastCall >= limit) {
      lastCall = now;
      func.apply(this, args)
    }
  }
}
